<?php
/**
 * Flea Site
 *
 * @copyright  Copyright (c) 2008 Movoin Studio (http://movoin.com)
 * @license    Apache License 2.0
 * @version    $Id: Uploader.php 130 2009-05-21 14:23:24Z movoin $
 */

/**
 * 文件上传助手
 *
 */
class Helper_Uploader
{
    private $_file;

    private $_isResize;

    private $_width;

    private $_height;

    private $_checktype;

    private $_uploadDir;

    private $_uploader;

    function Helper_Uploader($uploadDir, $checktype=null, $isResize=false, $width=0, $height=0)
    {
        $this->_isResize = $isResize;
        $this->_width = $width;
        $this->_height = $height;
        $this->_checktype = $checktype;
        $this->_uploadDir = $uploadDir;

        $this->_uploader =& FLEA::getSingleton( 'FLEA_Helper_FileUploader' );;
    }

    function isLoaded($file)
    {
        return $this->_uploader->isFileExist($file);
    }

    function upload($file)
    {
        if($this->_uploader->isFileExist($file)) {
            $this->_file = $this->_uploader->getFile($file);

            if($this->_checktype) {
                if(!$this->_file->check($this->_checktype)) {
                    js_alert('格式不正确，请上传 ' . $this->_checktype . ' 格式的文件', 'history.back(-1)');
                }
            }

            $uploadDir = $this->_uploadDir;
            $basename = md5(time() . $this->_file->getTmpName());
            $filename = $basename . '.' . $this->_file->getExt();

            if($this->_isResize) { $thumb = $this->reSize($filename); }

            $this->_file->move($uploadDir . DS . $filename);

            return array(
                    'main' => $filename,
                    'thumb' => $thumb
                );

        }
    }

    function reSize($filename)
    {
        FLEA::loadHelper('image');
        $image =& FLEA_Helper_Image::createFromFile($this->_file->getTmpName(), $this->_file->getExt());
        $image->crop($this->_width, $this->_height, true, true);
        $image->saveAsJpeg($this->_uploadDir . DS . 'thumb_' . $filename);
        $image->destory();
        return 'thumb_' . $filename;
    }

}
